use regex::Regex;

pub fn to_hex(number: u32) -> char {
    match number {
        0..=9 => (b'0' + number as u8) as char,
        10..=15 => (b'a' + (number - 10) as u8) as char,
        _ => unreachable!(),
    }
}

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    assert!(to_base >= 2 && to_base <= 16, "Base must be between 2 and 16");
    
    let re = Regex::new(r"(\d+)\((\d+)\)").unwrap();

    let n;
    let b;

    if let Some(captures) = re.captures(num_str) {
        n = captures.get(1).map_or("", |m| m.as_str());
        b = captures.get(2).map_or(0, |m| m.as_str().parse::<u32>().unwrap_or(0));
    }
    else {
        panic!("wrong input")
    }

    let mut n = u32::from_str_radix(&n, b).unwrap();

    let mut r = String::new();

    while n != 0 {
        let res = n % to_base;
        n /= to_base;
        r.push(to_hex(res));
    }

    r.chars().rev().collect()
}
